<template>
  <div class="imageUpload">
    <el-upload
      accept=".jpg,.png,.jpeg"
      :action="qiniuAction"
      :data="tokenData"
      :show-file-list="showFileList"
      :on-success="handleSuccess"
      :on-error="handleError"
      :before-upload="beforeUpload"
      :on-remove="handleRemove"
      :multiple="multiple"
      :limit="limit"
      :on-exceed="handleExceed"
      list-type="picture"
      :file-list="fileList"
    >
      <!-- <div class="img" v-if="value && url" v-bind:style="{'transform': rotate}">
                <img :src="url" :class="['logoImage', imgClass?imgClass:'']" ref="imgEl">
                <div :class="['close', rotate=='rotate(90deg)'?'r90':'']">
                    <i class="el-icon-circle-close" @click.prevent="del($event)"></i>
                </div>
			</div>-->

      <div style="position: relative">
        <div v-if="value && url" class="img">
          <img ref="imgEl" :src="url" :class="['logoImage', imgClass ? imgClass : '']" />
          <div class="close">
            <i class="el-icon-circle-close" @click.prevent="del($event)"></i>
          </div>
        </div>
        <div v-else class="el-upload el-upload--picture-card">
          <p class="tips">+ {{ tips }}</p>
          <input type="file" name="file" class="el-upload__input" />
        </div>
        <div v-show="localLoading" class="loading-icon">
          <i class="el-icon-loading"></i>
        </div>
      </div>
    </el-upload>
  </div>
</template>
<script>
import { mapState, mapActions } from 'vuex';
import { isArray, isObject } from 'lodash';
//
export default {
  props: {
    // 监控的值
    value: { type: [String, Number], default: '' },
    // 提示语
    tips: {
      type: String,
      default: '点击上传照片',
    },
    // 文件限制个数
    limit: {
      type: Number,
      default: 100,
    },
    // 是否多选
    multiple: {
      type: Boolean,
      default: false,
    },
    // 是否展示文件列表
    showFileList: {
      type: Boolean,
      default: false,
    },
    imgClass: {
      type: String,
      default: '',
    },
    loading: { type: Boolean, default: false },
    // 文件大小，单位M，默认5M
    maxSize: { type: Number, default: 5 },
    // 支持的扩展名
    supportExt: {
      type: Array,
      default: () => {
        return ['jpg', 'jpeg', 'png', 'gif'];
      },
    },
  },
  data() {
    return {
      fileList: [],
      qiniuAction: '//up-z0.qiniup.com',
      // qiniuAction: process.env.VUE_APP_UPLOAD_URL + '/intranet/upload/form',
      url: null,
      rotate: 'rotate(0deg)',
      localLoading: this.localLoading,
      fileNameKey: +new Date(),
    };
  },
  computed: {
    ...mapState('qiniu', ['tokenData']),
  },
  watch: {
    loading(newVal) {
      this.localLoading = newVal;
    },
    value: {
      handler(val) {
        if (val) {
          let fileArr = isArray(val) ? val : val.split(';');
          const urlList = fileArr.map(function(item) {
            if (item) {
              return { url: isObject(item) ? item.url : item };
            }
          });
          this.fileList = urlList[0] ? urlList : [];
          this.url = isArray(val) ? null : val;
        }
      },
      deep: true,
      immediate: true,
    },
  },

  mounted() {
    this.checkTokenData();
  },
  methods: {
    ...mapActions('qiniu', [
      'getTokenData',
      'checkTokenData',
      'updateFileNameKey',
      'refreshTokenData',
    ]),
    handleExceed() {
      this.$message.warning(`文件个数限制为` + this.limit);
    },
    beforeUpload(file) {
      const isJPG = /image\/[jpeg|jpg|png|gif]/.test(file.type);
      const isLt1M = file.size / 1024 / 1024 / this.maxSize < 1;
      if (!isJPG) {
        this.$message.warning('上传图片格式应为jpeg/jpg/png/gif');
      }
      if (!isLt1M) {
        this.$message.warning(`上传图片大小不能超过 ${this.maxSize}MB`);
      }
      if (isJPG && isLt1M) this.localLoading = true;
      return isJPG && isLt1M;
    },
    handleSuccess(response, file, fileList) {
      this.localLoading = false;
      let keys = [];
      const domain = this.tokenData.domain + '/';
      for (let i = 0; i < fileList.length; i++) {
        let url;
        if (fileList[i].response) {
          url = domain + fileList[i].response.key;
        } else {
          url = fileList[i].url;
        }
        keys.push(url + '?imageMogr2/auto-orient');
      }
      if (!this.multiple) {
        this.url = domain + response.key + '?imageMogr2/auto-orient';
        this.$emit('input', this.url);
      } else {
        this.$emit('input', keys.join(';'));
      }

      this.updateFileNameKey();
    },
    handleError() {
      this.localLoading = false;
      this.updateFileNameKey();
      this.$message.warning('上传异常，请重试');
      this.refreshTokenData();
    },
    handleRemove(file, fileList) {
      let keys = [];
      for (let i = 0; i < fileList.length; i++) {
        let url;
        if (fileList[i].response) {
          url = this.qiniuDomain + fileList[i].response.key;
        } else {
          url = fileList[i].url;
        }
        keys.push(url);
      }
      this.$emit('input', keys.join(';'));
    },
    del(event) {
      this.url = null;
      //   this.value = null;
      this.$emit('input', null);
      event.stopPropagation();
      return false;
    },
  },
};
</script>

<style lang="less">
.imageUpload {
  .el-upload-list__item {
    display: inline-block;
    width: auto !important;
  }
  .picture {
    display: inline-block;
    width: 48px;
    height: 48px;
  }
  .logoImage {
    width: 120px;
    height: auto;
    display: block;
  }
  .white-logo-imageUpload {
    background-color: #52c895 !important;
  }
  .img {
    width: 120px;
    height: auto;
    border: 1px solid #eee;
    position: relative;
    box-shadow: 0 0 3px 1px rgba(110, 110, 110, 0.4);
  }
  .close {
    width: 17px;
    height: 17px;
    line-height: 17px;
    border-radius: 50%;
    background: #fff;
    position: absolute;
    top: -8px;
    right: -8px;
    &.r90 {
      left: -8px;
    }
  }
  .loading-icon {
    position: absolute;
    top: 50%;
    left: 50%;
    font-size: 20px;
    margin-left: -20px;
    margin-top: -20px;
    background: rgba(0, 0, 0, 0.6);
    border-radius: 50%;
    width: 40px;
    height: 40px;
    text-align: center;
    line-height: 40px;
    i {
      color: #fff;
    }
  }
  .el-icon-circle-close {
    color: #267bf7;
    font-size: 17px;
  }
}
</style>
